var app = getApp();
var answerTimer = null;
function checkAnswer(that,num){
	var cur_num = parseInt(that.data.cur_num);
	var right_anwer = app.strencode(that.data.problem[cur_num].answer,that.data.str_time);
	var num1 = parseInt(num) + 1;
	var right_anwer1 = parseInt(right_anwer) + 1;
	if(right_anwer!=num1){
		if(cur_num>parseInt(that.data.g_nums[1])){
			app.tzfail(that,2);//挑战失败
		}
		else{
			var temp_problem = that.data.problem[cur_num];
			//that.data.problem[cur_num].answers[num].status = 'fail';
    		//that.data.problem[cur_num].answers[right_anwer1].status = 'success';
    		//是否分享-分享则继续答题
    		that.setData({problem:that.data.problem,showWrong:true,temp_problem:temp_problem});
    		that.audioCtx.pause()
		}
	}
	else{
    wx.showToast({
      title: '回答正确',
      icon: 'success',
      mask: true,
      duration: 1500,
    });

		if (cur_num+1 == parseInt(that.data.problem_num)) {
			setTimeout(function(){
        app.checkReward(that, 2, cur_num);//中奖了
      },1500);
			return false;
		}
		that.data.problem[cur_num].answers[num].status = 'success';
		that.setData({problem:that.data.problem});
		cur_num++;
		setTimeout(function(){
			var g_nums = that.data.g_nums;
			if(cur_num == parseInt(g_nums[0]) || cur_num == parseInt(g_nums[1])){
				//获取新的题目
				app.util.request({
	  				url: 'entry/wxapp/checkAnswer',
	  				data: {
	  					m: 'junsion_challeng',
	  					t: 1,
	  					mid:that.data.mem.id,
	  					str_time:that.data.str_time,
	  					game:2,
	  					p_num:cur_num
	  				},
	  				success: function (res) {
	  					if(res.data.code==1){
		  					that.setData({
		  						problem: that.data.problem.concat(res.data.problem),
		  	  	            });
		  					that.timeCountDown(that.data.times);
		  					that.setData({resettime:that.data.times,cur_num:cur_num,answerIng:false});
	  					}
	  					else{
	  						wx.showModal({
	  							title:res.data.msg,
	  							showCancel:false,
	  							success: function(res) {
	  								wx.redirectTo({
	  									url: '../index/index'
	  								})
	  							}
	  						});
	  					}
	  				}
	  			});
			}
			else{
				that.timeCountDown(that.data.times);
				that.setData({resettime:that.data.times,cur_num:cur_num,answerIng:false});
			}
        },1500);
	}
}
Page({
	onShareAppMessage:function(){
	  var that = this;
	  var mid = that.data.mem.id;
	  var sharedata = that.data.shareData;
	  sharedata.path = 'challeng/pages/index/index?mid='+mid+'&gType=2';
	  return {
		  title: sharedata.title,
	    //  desc: sharedata.desc,
	      path: sharedata.path,
	      imageUrl:sharedata.pic,
	      success(res){
	    	  var shareTicket = res.shareTickets[0] // 获取 shareTicket
	    	  wx.getShareInfo({
	              shareTicket: shareTicket,
	              complete(res) {
	            	  app.util.request({
		    	        url: 'entry/wxapp/reAnswer',
		    	        data: {
		    	            m : 'junsion_challeng',
		    	            t : 1,
		    	            mid : that.data.openid,
		    	            iv : res.iv,
		    	            encryptedData : res.encryptedData,
		    	        },
		    	        success: function (res) {
		    	        	 if(res.data.code == 2){
		    	        		 that.audioCtx.play();
		    	        		 clearInterval(answerTimer);
		    	        		 var cur_num = parseInt(that.data.cur_num);
		    	        		 var problem = that.data.problem;
		    	        		 problem[cur_num] = that.data.temp_problem;
		    	        		 that.setData({
		    	        			 answerIng:false,
		    	        			 showWrong:false,
		    	        			 problem:problem,
		    	        			 resettime:that.data.times
		    	        		 });
		    	        	 }
		    	        	 else{
		    	        		 wx.showModal({title:res.data.msg,showCancel:false});
		    	        	 }
		    	        }
		    	    }); 
	                
	              }
	          });
	      },
	      fail: function(res) {
	        // 转发失败
	    	  console.log(res);
	      }
	  }
  },
    data:{
    	openid:'',
    	mem:{},
    	problem:{},
    	temp_problem:{},
    	times:10,
    	g_nums:[],
    	resettime:10,
    	problem_num:0,
    	cur_num:0,
    	g_over:'',
    	g_close:'',
    	g_shoushi:'',
    	audioCtx:'',
    	errAudio:'',
    	gametoken:'',
    	game_bg:'',
        answerIng : false,
        showWrong : false,
    	
        beginCountDown: 5,//游戏开始--倒计时
        gamingStatus: 'notBegin',//游戏状态4个。notBegin未开始，running正在运行，fail挑战失败,success挑战成功
    },
    onLoad:function(options){
    	var that = this;
    	wx.showLoading({title:'数据加载中...'});
    	app.sysInit(this,function(res){
	    	app.getUserInfo(function (res) {
	        	var openid = res['openid'];
	        	//获取分享内容
	            app.getShareData(function(res){
	            	that.setData({shareData:res.data});
	            },openid,2);
	            
	        	that.setData({openid:openid});
	        	app.util.request({
			        url: 'entry/wxapp/tplay',
			        data: {
			          m: 'junsion_challeng',
			          t: 1,
			          openid:openid,
			          game:2,
			        },
			        success: function (res) {
			          wx.hideLoading();
			          if(res.data.code==0 || res.data.code==2){
			        	  var code = res.data.code;
			        	  wx.showModal({
			                  title:res.data.msg,
			                  showCancel:false,
			                  success: function(res) {
			                	  wx.showLoading({title:'数据加载中...'});
			                	  if(code==2)
			                		  var url = '../index/index?gobuy=1';
			                	  else var url = '../index/index';
			                	  wx.redirectTo({
			    	    			  url: url
			    	    		  })
			                  }
		                  });
			          }
			          else{
			        	  that.setData({
			        		  game_bg:res.data.game_bg,
			        		  str_time:res.data.str_time,
			        		  beginCountDown:res.data.down,
			        		  gametoken:res.data.gametoken,
			        		  mem:res.data.mem,
			        		  problem:res.data.problem,
			        		  times:res.data.times,
			        		  g_nums:res.data.g_nums,
			        		  resettime:res.data.times,
			        		  problem_num:res.data.problem_num,
			        		  g_close:res.data.g_close,
			        		  g_shoushi:res.data.g_shoushi,
			        		  g_over:res.data.g_over,
			        		  answerIng:false,
			        		  
			        	  });
			        	  that.beginCountDown(res.data.down);//游戏主入口
			          }
			        },
			    });
	    	});
	    });
        var music = wx.getStorageSync('music');
        that.setData({
  		  music:music.music,
  		  err_music:music.err_music,
  	    });
    },
    hideWrong:function(){
  	  var that = this;
  	  that.audioCtx.pause()
  	  app.tzfail(that,2);//挑战失败
  	  that.setData({
  		  showWrong:false,
  	  });
    },
    goCheck:function(e){
    	var that = this;
    	if(that.data.answerIng) return false;
    	var dataset = e.currentTarget.dataset;
    	var index = dataset.index;
    	that.setData({answerIng:true});
    	checkAnswer(that,index);
    	return false;
    },
    onReady: function () {
    	var that=this;
    	this.audioCtx = wx.createAudioContext('myAudio')
        this.errAudio = wx.createAudioContext('errAudio')
        this.audioCtx.play()
    },
    onUnload: function(){
  	  clearInterval(answerTimer);
    },
    timeCountDown:function(myTime){
    	var that=this;
    	if(answerTimer){
    		clearInterval(answerTimer);
    		that.setData({ resettime: myTime });
    	}
		answerTimer = setInterval(function () {
    		if(that.data.answerIng){
    			return false;
    		}
    		that.setData({ resettime: --myTime });
    		if (myTime <= 0) {
    			//时间到，失败
    			clearInterval(answerTimer);
    			//失败处理
    			that.audioCtx.pause()
    			app.tzfail(that,2);//挑战失败
    		}
    	}, 1000);
    	
    },
 // 游戏开始倒计时
    beginCountDown:function(countTime){
        var that=this;
        var timer = setInterval(function () {
            that.setData({ beginCountDown: --countTime });
            if (countTime <= 0) {
                clearInterval(timer);
                that.setData({
                    gamingStatus:'running'
                });
                that.timeCountDown(parseInt(that.data.times));//游戏主入口
            }
        }, 1000)
    }
})